import { defineStore } from "pinia";
import { store } from "@/store";
import { routerArrays } from "@/layout/types";
import { responsiveStorageNameSpace } from "@/config";
import type { multiType, positionType } from "./types";
import { isEqual, isUrl, storageLocal } from "@pureadmin/utils";
import { PxMessageBox } from "px-ui";

export const useMultiTagsStore = defineStore({
  id: "pure-multiTags",
  state: () => ({
    isToticed: false,
    // 存储标签页信息（路由信息）
    multiTags: storageLocal().getItem<StorageConfigs>(`${responsiveStorageNameSpace()}configure`)?.multiTagsCache
      ? storageLocal().getItem<StorageConfigs>(`${responsiveStorageNameSpace()}tags`)
      : [...routerArrays],
    multiTagsCache: storageLocal().getItem<StorageConfigs>(`${responsiveStorageNameSpace()}configure`)?.multiTagsCache
  }),
  persist: {
    pick: ["isToticed"]
  },
  getters: {
    getMultiTagsCache(state) {
      return state.multiTagsCache;
    }
  },
  actions: {
    ISTOTICED(flag: boolean) {
      this.isToticed = flag;
    },
    multiTagsCacheChange(multiTagsCache: boolean) {
      this.multiTagsCache = multiTagsCache;
      if (multiTagsCache) {
        storageLocal().setItem(`${responsiveStorageNameSpace()}tags`, this.multiTags);
      } else {
        storageLocal().removeItem(`${responsiveStorageNameSpace()}tags`);
      }
    },
    tagsCache(multiTags) {
      this.getMultiTagsCache && storageLocal().setItem(`${responsiveStorageNameSpace()}tags`, multiTags);
    },
    handleTags<T>(mode: string, value?: T | multiType, position?: positionType): T {
      switch (mode) {
        case "equal":
          this.multiTags = value;
          this.tagsCache(this.multiTags);
          break;
        case "push":
          {
            const tagVal = value as multiType;
            // 隐藏多页签列表
            const hiddenTagList = ["/all/visual/building", "/all/visual/floor", "/all/visual/room", "/all/visual/equipment"];
            if (hiddenTagList.indexOf(tagVal.path) !== -1) {
              return;
            }
            // 不添加到标签页
            if (tagVal?.meta?.hiddenTag) return;
            // 如果是外链无需添加信息到标签页
            if (isUrl(tagVal?.name)) return;
            // 如果title为空拒绝添加空信息到标签页
            if (tagVal?.meta?.title.length === 0) return;
            // showLink:false 不添加到标签页
            // if (isBoolean(tagVal?.meta?.showLink) && !tagVal?.meta?.showLink)
            //   return;
            const tagPath = tagVal.path;
            // 判断tag是否已存在
            const tagHasExits = this.multiTags.some(tag => tag.path === tagPath);
            // 获取tag索引值
            const tagIndex = this.multiTags.findIndex(tag => tag.path === tagPath);

            // 判断tag中的query键值是否相等
            const tagQueryHasExits = this.multiTags.some(tag => {
              return isEqual(tag?.query, tagVal?.query);
            });

            // 判断tag中的params键值是否相等
            const tagParamsHasExits = this.multiTags.some(tag => {
              return isEqual(tag?.params, tagVal?.params);
            });

            // if (tagHasExits && tagQueryHasExits && tagParamsHasExits) return;
            if (tagHasExits && (tagQueryHasExits || tagParamsHasExits)) {
              if (tagIndex === -1) return;

              this.multiTags.splice(tagIndex, 1, tagVal);
              return;
            }

            // 动态路由可打开的最大数量
            const dynamicLevel = tagVal?.meta?.dynamicLevel ?? -1;
            if (dynamicLevel > 0) {
              if (this.multiTags.filter(e => e?.path === tagPath).length >= dynamicLevel) {
                // 如果当前已打开的动态路由数大于dynamicLevel，替换第一个动态路由标签
                // const tagIndex = this.multiTags.findIndex(item => item?.path === tagPath);
                tagIndex !== -1 && this.multiTags.splice(tagIndex, 1);
              }
            }

            if (tagHasExits) {
              this.multiTags.splice(tagIndex, 1);
              this.multiTags.splice(1, 0, value);
            } else {
              this.multiTags.splice(1, 0, value);
            }

            if (this.multiTags.length > 30) {
              if (this.isToticed) {
                this.multiTags.splice(30);
                this.tagsCache(this.multiTags);
              } else {
                const message = "当前已打开30个系统页签，超过30个页签后系统将按顺序关闭最右侧的页签！";
                PxMessageBox.alert(message, "注意", {
                  confirmButtonText: "不再提醒",
                  type: "warning",
                  callback: () => {
                    this.multiTags.splice(30);
                    this.tagsCache(this.multiTags);
                    this.isToticed = true;
                  }
                });
              }
            } else {
              this.tagsCache(this.multiTags);
            }
          }
          break;
        case "splice":
          if (!position) {
            const index = this.multiTags.findIndex(v => v.path === value);
            if (index === -1) return;
            this.multiTags.splice(index, 1);
          } else {
            this.multiTags.splice(position?.startIndex, position?.length);
          }
          this.tagsCache(this.multiTags);
          return this.multiTags;
        case "slice":
          return this.multiTags.slice(-1);
      }
    },
    sortTags(value?: ToRouteType) {
      // 判断tag是否已存在
      const tagIndex = this.multiTags.findIndex(tag => {
        return tag.path === value.path;
      });
      if (tagIndex > 1) {
        const t = this.multiTags[tagIndex];
        this.multiTags.splice(tagIndex, 1);
        this.multiTags.splice(1, 0, t);
      }
    }
  }
});

export function useMultiTagsStoreHook() {
  return useMultiTagsStore(store);
}
